﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Gao.Poker.Domain;

namespace Gao.Poker.Services
{
    public class TablesService : BaseService
    {
        public List<Tables> SearchTables()
        {
            return DbContext.Tableses.ToList();
        }

        public List<Tables> GetTables(int competitionID)
        {
            var seatings =
                DbContext.Seatings.Where(a => a.CompetitionID == competitionID).Select(a => a.TableNum).ToList();
            List<Tables> tableses = DbContext.Tableses.Where(a => a.Available == 0 || seatings.Contains(a.Number)).ToList();
            return tableses;
        }

        public Tables Save(Tables tables)
        {
            if (tables == null) return null;

            if (tables.ID == 0)
            {
                DbContext.Tableses.Add(tables);
            }
            else
            {
                DbContext.Tableses.Attach(tables);
                DbContext.Entry(tables).State = EntityState.Modified;
            }

            Trace.WriteLine(DbContext.ToString());
            DbContext.SaveChanges();
            return tables;
        }

        public void Update(int competitionID)
        {
            var seatings = DbContext.Seatings.Where(a => a.CompetitionID == competitionID).Select(a => a.TableNum).ToList();
            List<Tables> tableses = DbContext.Tableses.Where(a => seatings.Contains(a.Number)).ToList();
            foreach (var table in tableses )
            {
                table.Available = 0;
            }
            DbContext.SaveChanges();
        }
    }
}
